/**
 * 权限控制工具
 *
 * 基于用户角色和权限标识进行访问控制
 * 支持前端路由权限验证和组件级权限控制
 */

import { useUserStore } from "@/store/modules/user";
import type { RouteLocationNormalized } from "vue-router";

/**
 * 权限验证接口
 */
export interface PermissionChecker {
  /**
   * 检查用户是否拥有指定权限
   */
  hasPermission(permission: string | string[]): boolean;

  /**
   * 检查用户是否拥有指定角色
   */
  hasRole(role: string | string[]): boolean;

  /**
   * 检查路由是否有权限访问
   */
  hasRoutePermission(route: RouteLocationNormalized): boolean;
}

/**
 * WMS 权限标识常量
 */
export const WMS_PERMISSIONS = {
  // 商品管理权限
  ITEM: {
    LIST: "wms:item:list",
    ADD: "wms:item:add",
    EDIT: "wms:item:edit",
    DELETE: "wms:item:delete",
    SKU: "wms:item:sku",
    IMPORT: "wms:item:import",
    EXPORT: "wms:item:export",
  },

  // 仓库管理权限
  WAREHOUSE: {
    LIST: "wms:warehouse:list",
    ADD: "wms:warehouse:add",
    EDIT: "wms:warehouse:edit",
    DELETE: "wms:warehouse:delete",
    EXPORT: "wms:warehouse:export",
  },

  // 库区管理权限
  AREA: {
    LIST: "wms:area:list",
    ADD: "wms:area:add",
    EDIT: "wms:area:edit",
    DELETE: "wms:area:delete",
    EXPORT: "wms:area:export",
  },

  // 商户管理权限
  MERCHANT: {
    LIST: "wms:merchant:list",
    ADD: "wms:merchant:add",
    EDIT: "wms:merchant:edit",
    DELETE: "wms:merchant:delete",
    EXPORT: "wms:merchant:export",
  },

  // 库存管理权限
  INVENTORY: {
    LIST: "wms:inventory:list",
    ADJUST: "wms:inventory:adjust",
    ALLOCATE: "wms:inventory:allocate",
    HISTORY: "wms:inventory:history",
    EXPORT: "wms:inventory:export",
  },

  // 入库单权限
  RECEIPT: {
    ALL: "wms:receipt:all",
    LIST: "wms:receipt:list",
    ADD: "wms:receipt:add",
    EDIT: "wms:receipt:edit",
    DELETE: "wms:receipt:delete",
    CONFIRM: "wms:receipt:confirm",
    CANCEL: "wms:receipt:cancel",
    EXPORT: "wms:receipt:export",
  },

  // 出库单权限
  SHIPMENT: {
    ALL: "wms:shipment:all",
    LIST: "wms:shipment:list",
    ADD: "wms:shipment:add",
    EDIT: "wms:shipment:edit",
    DELETE: "wms:shipment:delete",
    CONFIRM: "wms:shipment:confirm",
    CANCEL: "wms:shipment:cancel",
    EXPORT: "wms:shipment:export",
  },

  // 移库单权限
  MOVEMENT: {
    LIST: "wms:movement:list",
    ADD: "wms:movement:add",
    EDIT: "wms:movement:edit",
    DELETE: "wms:movement:delete",
    CONFIRM: "wms:movement:confirm",
    EXPORT: "wms:movement:export",
  },

  // 盘点单权限
  CHECK: {
    LIST: "wms:check:list",
    ADD: "wms:check:add",
    EDIT: "wms:check:edit",
    DELETE: "wms:check:delete",
    CONFIRM: "wms:check:confirm",
    EXPORT: "wms:check:export",
  },

  // 报表权限
  REPORT: {
    INVENTORY: "wms:report:inventory",
    ORDER: "wms:report:order",
  },
} as const;

/**
 * 用户角色常量
 */
export const USER_ROLES = {
  SUPER_ADMIN: "admin",
  WMS_ADMIN: "wms_admin",
  WMS_USER: "wms_user",
  WAREHOUSE_MANAGER: "warehouse_manager",
  INVENTORY_CLERK: "inventory_clerk",
} as const;

/**
 * 权限检查器实现
 */
class PermissionCheckerImpl implements PermissionChecker {
  /**
   * 检查字符权限
   * @param value 权限标识，支持字符串或字符串数组
   * @returns 是否有权限
   */
  hasPermission(value: string | string[]): boolean {
    if (!value) {
      console.error("权限标识不能为空");
      return false;
    }

    const userStore = useUserStore();
    const permissions = userStore.permissions || [];
    const permissionList = Array.isArray(value) ? value : [value];
    const allPermission = "*:*:*";

    // 检查是否有超级权限
    if (permissions.includes(allPermission)) {
      return true;
    }

    // 检查是否有任一指定权限
    return permissionList.some((permission) =>
      permissions.includes(permission),
    );
  }

  /**
   * 检查角色权限
   * @param value 角色标识，支持字符串或字符串数组
   * @returns 是否有角色
   */
  hasRole(value: string | string[]): boolean {
    if (!value) {
      console.error("角色标识不能为空");
      return false;
    }

    const userStore = useUserStore();
    const roles = userStore.roles || [];
    const roleList = Array.isArray(value) ? value : [value];
    const superAdmin = "admin";

    // 检查是否是超级管理员
    if (roles.includes(superAdmin)) {
      return true;
    }

    // 检查是否有任一指定角色
    return roleList.some((role) => roles.includes(role));
  }

  /**
   * 检查路由权限
   * @param route 路由对象
   * @returns 是否有访问权限
   */
  hasRoutePermission(route: RouteLocationNormalized): boolean {
    const { meta } = route;

    // 如果路由没有权限要求，直接允许访问
    if (!meta) {
      return true;
    }

    const { roles, permissions, authList } = meta;

    // 检查角色权限
    if (roles && roles.length > 0) {
      if (!this.hasRole(roles)) {
        return false;
      }
    }

    // 检查字符权限
    if (permissions && permissions.length > 0) {
      if (!this.hasPermission(permissions)) {
        return false;
      }
    }

    // 检查WMS专用权限列表
    if (authList && Array.isArray(authList) && authList.length > 0) {
      const authMarks = authList.map((item) => item.authMark);
      if (!this.hasPermission(authMarks)) {
        return false;
      }
    }

    return true;
  }
}

/**
 * 导出权限检查器实例
 */
export const permissionChecker: PermissionChecker = new PermissionCheckerImpl();

/**
 * 检查权限的便捷函数
 * @param permission 权限标识
 * @returns 是否有权限
 */
export function checkPermission(permission: string | string[]): boolean {
  return permissionChecker.hasPermission(permission);
}

/**
 * 检查角色的便捷函数
 * @param role 角色标识
 * @returns 是否有角色
 */
export function checkRole(role: string | string[]): boolean {
  return permissionChecker.hasRole(role);
}

/**
 * 检查路由权限的便捷函数
 * @param route 路由对象
 * @returns 是否有访问权限
 */
export function checkRoutePermission(route: RouteLocationNormalized): boolean {
  return permissionChecker.hasRoutePermission(route);
}

/**
 * 权限指令辅助函数
 * 用于 v-permission 指令
 */
export function hasPermissionDirective(
  el: Element,
  binding: { value: string | string[] },
): boolean {
  const { value } = binding;
  const hasAuth = checkPermission(value);

  if (!hasAuth) {
    el.parentNode?.removeChild(el);
  }

  return hasAuth;
}

/**
 * 角色指令辅助函数
 * 用于 v-role 指令
 */
export function hasRoleDirective(
  el: Element,
  binding: { value: string | string[] },
): boolean {
  const { value } = binding;
  const hasAuth = checkRole(value);

  if (!hasAuth) {
    el.parentNode?.removeChild(el);
  }

  return hasAuth;
}

// 默认导出
export default {
  permissionChecker,
  checkPermission,
  checkRole,
  checkRoutePermission,
  hasPermissionDirective,
  hasRoleDirective,
  WMS_PERMISSIONS,
  USER_ROLES,
};
